import 'dart:convert';
import 'package:base_flutter/base_flutter.dart';
import 'package:dio/dio.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:ls_work/a_elder/models/waiting_right_entity.dart';
import 'package:ls_work/a_yyt/models/gean_daiban_detail_entity.dart';
import 'package:ls_work/a_yyt/models/pending_selected_group_entity.dart';
import 'package:ls_work/a_yyt/page/pending_single_Staff_page.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/res/styles.dart';
import 'package:ls_work/util/app_navigator.dart';
import 'package:ls_work/util/toast.dart';

import '../../util/flat_button.dart';



///评估审核
class PendingBizType1052 extends StatefulWidget {
  final WaitingRighInfo? info;
  final VoidCallback? callBack;
  PendingBizType1052({Key? key, this.info, this.callBack});
  @override
  _PendingBizType1052State createState() => _PendingBizType1052State();
}

class _PendingBizType1052State extends State<PendingBizType1052> {
  List<PendingSelectedGroupInfo> _selectedList = [];
  List<PendingSelectedGroupInfo> _executeHumanList = [];
  List<PendingSelectedGroupEntity> orginList = [];
  GeAnWaitingBeanInfo beanModel = GeAnWaitingBeanInfo(records: []);
  TextEditingController textFieldEditer = TextEditingController();
  int _groupValue = 1;
  // String nurseLevel = '';
  // int nurseLevelId = 0;

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      fectElderTimeLine();
      _getAllByCurBranchWithUsers();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('个案审核'),
        elevation: 0.5,
      ),
      body: Stack(
        fit: StackFit.expand,
        children: <Widget>[
          SingleChildScrollView(
            padding: EdgeInsets.fromLTRB(15, 30, 15, 80),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text.rich(TextSpan(children: [
                  TextSpan(
                    text: '   长者：',
                    style: TextStyles.textGray18,
                  ),
                  TextSpan(
                    text: '${beanModel.elderName ?? ''}',
                    style: TextStyles.textDark18,
                  ),
                ])),
                Gaps.vGap16,
                Gaps.vGap16,
                Text.rich(TextSpan(children: [
                  TextSpan(
                    text: '   处理时间：',
                    style: TextStyles.textGray18,
                  ),
                  TextSpan(
                    text: '${beanModel.deadline ?? ''}',
                    style: TextStyles.textDark18,
                  ),
                ])),
                Gaps.vGap16,
                Gaps.vGap16,
                Text(
                  '    发起原因',
                  style: TextStyles.textDark18,
                ),
                Gaps.vGap16,
                Container(
                  width: double.infinity,
                  padding: EdgeInsets.all(8),
                  margin: EdgeInsets.only(left: 15),
                  decoration: BoxDecoration(
                    color: Colours.bg_color,
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Text(
                    '${beanModel.reason ?? ''}',
                    style: TextStyles.textDark18,
                  ),
                ),
                Gaps.vGap16,
                Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: (beanModel.records??[]).map((e) {
                    return Container(
                      padding: EdgeInsets.fromLTRB(0, 10, 0, 10),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        // crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text(
                            '    ${e.operator ?? ''}',
                            style: TextStyles.textDark18,
                          ),
                          Expanded(child: Gaps.hGap12),
                          Container(
                            width: ScreenUtil.getScreenW(context) - 114,
                            padding: EdgeInsets.all(8),
                            decoration: BoxDecoration(
                              color: Colours.bg_color,
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: Text(
                              '${e.remark ?? ''}',
                              style: TextStyles.textDark18,
                            ),
                          ),
                        ],
                      ),
                    );
                  }).toList(),
                ),
                Gaps.vGap16,
                Gaps.vGap16,
                Container(
                  width: ScreenUtil.getScreenW(context),
                  height: 50,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Flexible(
                        child: Text(
                          '   审核结果：',
                          style: TextStyles.textDark20,
                        ),
                      ),
                      Flexible(
                        child: RadioListTile(
                          value: 1,
                          title: Text('审核通过'),
                          groupValue: _groupValue,
                          onChanged: (value) {
                            setState(() {
                              _groupValue = value!;
                            });
                          },
                        ),
                      ),
                      Flexible(
                        child: RadioListTile(
                          value: 0,
                          title: Text('继续执行'),
                          groupValue: _groupValue,
                          onChanged: (value) {
                            setState(() {
                              _groupValue = value!;
                            });
                            if (value == 0) {
                              AppNavigator.push(
                                context,
                                PendingSingleStaffPage(
                                  orginList: orginList,
                                  callBack: (selectedList) {
                                    setState(() {
                                      _selectedList = selectedList;
                                    });
                                  },
                                ),
                              );
                            }
                          },
                        ),
                      ),
                    ],
                  ),
                ),
                _groupValue == 0
                    ? Container(
                        padding: EdgeInsets.only(
                            right: (ScreenUtil.getScreenW(context) - 80) / 3.0),
                        alignment: Alignment.centerRight,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: _selectedList.map((e) {
                            return Padding(
                              padding: EdgeInsets.all(10),
                              child: Text(
                                '${e.userName}',
                                style: TextStyles.textDark18,
                              ),
                            );
                          }).toList(),
                        ),
                      )
                    : Container(),
                Gaps.vGap50,
                Gaps.line,
                Gaps.vGap16,
                Text(
                  '   *备注',
                  style: TextStyles.textGray18,
                ),
                Container(
                  padding: EdgeInsets.all(20),
                  color: Colors.white,
                  alignment: Alignment.topLeft,
                  height: 150,
                  child: TextField(
                    controller: textFieldEditer,
                    maxLines: 5,
                    maxLength: 150,
                    autofocus: false,
                    decoration: InputDecoration(
                      hintText: "请输入备注内容",
                      hintMaxLines: 20,
                      fillColor: Colours.bg_color,
                      filled: true,
                      border: InputBorder.none,
                    ),
                  ),
                ),
              ],
            ),
          ),
          Positioned(
            bottom: 30,
            left: 0,
            right: 0,
            child: SizedBox(
              width: ScreenUtil.getScreenW(context),
              height: 50,
              child: FlatsButton(
                color: Colors.blue,
                highlightColor: Colors.blue[700]!,
                
                child: Text("提交"),
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(25.0)),
                onPressed: _send,
              ),
            ),
          ),
        ],
      ),
    );
  }

  void fectElderTimeLine() {
    var map = {
      'id': widget.info?.bizId,
      'onlyDealRecord': true,
      'wrapper': true,
    };

    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post(HttpApi.bizServiceCaseDetail, data: map,options: PostRequest.urlencodedHeader)
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            GeAnWaitingDetailEntity model =
                GeAnWaitingDetailEntity.fromJson(map['data']);
            setState(() {
              beanModel = model.bean!;
            });
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  ///获取分组
  void _getAllByCurBranchWithUsers() {
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post(
          HttpApi.getAllByCurBranchWithUsers,
        )
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            PendingSelectedGroupSection model =
                PendingSelectedGroupSection.fromJson(map);
            orginList = model.data!;
            if (beanModel.executeHumanList != null &&
                beanModel.executeHumanList!.length > 0) {
              for (var executeHumanInfo in (beanModel.executeHumanList??<GeAnWaitingRecordInfo>[])) {
                for (var item in orginList) {
                  for (var userInfo in (item.user??<PendingSelectedGroupInfo>[])) {
                    if (executeHumanInfo.id == userInfo.humanId) {
                      setState(() {
                        userInfo.isSelected = true;
                        _selectedList.add(userInfo);
                        _executeHumanList.add(userInfo);
                      });
                    }
                  }
                }
              }
            }
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  ///提交
  void _send() {
    FocusScope.of(context).unfocus();
    if (TextUtil.isEmpty(textFieldEditer.text)) {
      Toast.show('请输入备注');
      return;
    }
    var map = {
      'id': widget.info?.bizId,
      'auditType': _groupValue,
      'operType': 7,
      'remark': textFieldEditer.text,
    };
    if (_selectedList.length > 0) {
      var tempLList = [];
      for (var item in _selectedList) {
        tempLList.add(
            {'id': item.humanId, 'name': item.userName, 'status': item.status});
      }
      map['executeHumanList'] = tempLList;
    }

    if (_executeHumanList.length > 0) {
      var tempLList = [];
      for (var item in _executeHumanList) {
        if (!_selectedList.contains(item)) {
          tempLList.add({
            'id': item.humanId,
            'name': item.userName,
            'status': item.status
          });
        }
      }
      if (tempLList.length > 0) map['removeHumanList'] = tempLList;
    }
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post(HttpApi.bizServiceCaseAudit,
            data: {'jsonStr': jsonEncode(map)},options: PostRequest.urlencodedHeader)
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          Toast.show(map["msg"]);
          if(widget.callBack!=null){
            widget.callBack!();
          }
          Navigator.pop(context);
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }
}
